package com.gxc.oauth2.config.server;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.JdbcApprovalStore;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import javax.sql.DataSource;


/**
 * 认证服务配置类(开启认证服务注解).
 *
 * @author GongXincheng
 * @since 2019-10-11 01:45
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

/*    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        // 配置数据源（注意，我使用的是 HikariCP 连接池），以上注解是指定数据源，否则会有冲突
        return DataSourceBuilder.create().build();
    }*/

    @Autowired
    private DataSource dataSource;

    @Bean
    public ClientDetailsService jdbcClientDetails() {
        // 基于 JDBC 实现，需要事先在数据库配置客户端信息
        return new JdbcClientDetailsService(dataSource);
    }

    @Bean
    public TokenStore tokenStore() {
        // 基于 JDBC 实现，令牌保存到数据
        return new JdbcTokenStore(dataSource);
    }


    @Bean
    public ApprovalStore approvalStore() {
        // 用于保存，检索和撤销用户批准的界面
        return new JdbcApprovalStore(dataSource);
    }

    @Bean
    protected AuthorizationCodeServices authorizationCodeServices() {
        // 保存授权码.
        return new JdbcAuthorizationCodeServices(dataSource);
    }


    /**
     * 对客户端认证授权的配置（返回授权码）.
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        // 1：基于内存存储令牌，内存配置
//        clients.inMemory()
//                // 设置客户端标识
//                .withClient("client")
//                // 设置客户端安全码：必须进行加密
//                .secret(passwordEncoder.encode("secret"))
//                // 客户端授权类型：授权码模式
//                .authorizedGrantTypes("authorization_code")
//                // 客户端授权范围
//                .scopes("app")
//                // 注册回调地址, 授权码的回调地址
//                .redirectUris("https://www.funtl.com");

        // 2：数据库存储令牌
        // 读取客户端配置
        clients.withClientDetails(jdbcClientDetails());
    }


    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 设置令牌
        endpoints.approvalStore(approvalStore())
                .authorizationCodeServices(authorizationCodeServices())
                .tokenStore(tokenStore());
    }
}
